<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <rx-layout>
            <div slot="center">
                <a-form :form="form">
                    <a-form-item style="display:none">
                        <a-input v-decorator="['id']"/>
                        <a-input v-decorator="['appId',{initialValue:curApp.appId}]"/>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.routingName','路由名称')">
                        <a-input :placeholder="i18n('form.routingName','路由名称')"
                                 v-decorator="['routingName', {rules: [{required: true, message: i18n('form.routingName','路由名称','input')}]}]"/>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.routingType','路由类型')">
                        <a-select :placeholder="i18n('form.routingType','路由类型')" :getPopupContainer="p=>p.parentNode" :options="routeTypeList"  v-decorator="['routeType', {rules: [{required: true, message: i18n('form.routingType','路由类型','select')}]}]" />
                    </a-form-item>
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.condition','条件')">
                        <PredicateList ref="predicates" :predicates="predicates"></PredicateList>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.filter','过滤器')">
                        <FilterList ref="filters" :filters="filters"></FilterList>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.uri','目标路径')">
                        <a-input :placeholder="i18n('form.uri','目标路径')" v-decorator="['uri', {rules: [{required: true, message: i18n('form.uri','目标路径','input')}]}]"/>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.remark','备注')">
                        <a-input :placeholder="i18n('form.remark','备注')" v-decorator="['remark', {rules: [{required: false, message: i18n('form.remark','备注','input')}]}]"/>
                    </a-form-item>
                    <a-form-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.status','状态')">
                        <a-radio-group :placeholder="i18n('form.status','状态')" defaultValue="0" v-decorator="['status', {initialValue:'0',rules: [{required: true, message: i18n('form.status','状态','select')}]}]">
                            <a-radio value="1">{{i18n('form.publish','发布')}}</a-radio>
                            <a-radio value="0">{{i18n('form.prohibit','禁止')}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </rx-layout>
    </rx-dialog>
</template>
<script>
  import SysRoutingApi from '@/api/system/core/sysRouting'
  import SysRouteTypeApi from '@/api/system/core/sysRouteType'
  import {BaseForm, RxDialog,RxLayout,Util} from "@lowcode/jpaas-common-lib";
  import PredicateList from './PredicateList'
  import FilterList from './FilterList'
  export default {
    name: 'SysRoutingEdit',
    mixins: [BaseForm],
    components: {
      RxDialog,
      RxLayout,
      PredicateList,
      FilterList
    },
    data() {
      return {
        predicates: [],
        filters: [],
        requestData:[],
        type: "",
        routeTypeList:[],
      }
    },
    created() {
      this.getRoutingApi();
      this.getRouteTypeList();
      if (this.pkId) {
        this.type = "update";
      } else {
        this.type = "add";
      }
    },
    methods: {
      i18n(name,text,key){
          return this.$ti18(name,text,"SysRouting",key);
      },
      onload_(values) {
        if(values){
          if (values.condition&&values.condition != "") {
            var condition = values.condition.split(",");
            var conditionParameters = this.substr([],values.conditionParameters,condition.length);
            for (var i = 0; i < condition.length; i++) {
              var predicateObj = {
                name: condition[i],
                args: conditionParameters[i]
              };
              this.predicates.push(predicateObj);
            }
          }
          if (values.filter&&values.filter != "") {
            var filter = values.filter.split(",");
            var filterParameters = this.substr([],values.filterParameters,filter.length);;
            for (var i = 0; i < filter.length; i++) {
              var filterObj = {
                name: filter[i],
                args: filterParameters[i]
              };
              this.filters.push(filterObj);
            }
          }
        }
      },
      getRouteTypeList(){
        SysRouteTypeApi.getRouteTypeList().then(res=>{
          for (var i=0;i<res.length;i++){
            var obj={label:res[i].routeTypeName, value: res[i].id};
            this.routeTypeList.push(obj);
          }
        });
      },
      get(id) {
        return SysRoutingApi.get(id);
      },
      save(values) {
        var self = this;
        var flag=false;
        this.form.validateFields((err, data) => {
          if (!err) {
            if(self.type == "add"){
              var id = Util.randomId();
              values.id=id;
              data.id=id;
            }
            var predicates = self.$refs.predicates.predicateList;
            var filters = self.$refs.filters.filterList;
            var predicateName = "";
            var predicateArgs = "";
            var filterName = "";
            var filterArgs = "";
            for (var i = 0; i < predicates.length; i++) {
              if (i != 0) {
                predicateName += ",";
                predicateArgs += ",";
              }
              predicateName += predicates[i].predicateName;
              predicateArgs += predicates[i].predicateArgs;
            }
            data["condition"] = predicateName;
            data["conditionParameters"] = predicateArgs;
            for (var i = 0; i < filters.length; i++) {
              if (i != 0) {
                filterName += ",";
                filterArgs += ",";
              }
              filterName += filters[i].filterName;
              filterArgs += filters[i].filterArgs;
            }
            data["filter"] = filterName;
            data["filterParameters"] = filterArgs;
          }
          self.updateRoutes(values);
          values = data;
        });
        if(this.type=="add"){
          return SysRoutingApi.save(values);
        }else {
          return SysRoutingApi.update(values);
        }
      },
      getRoutingApi() {
        var self = this;
        SysRoutingApi.getRoutingApi().then(res => {
            if(res.success){
                self.requestData=res.data;
            }
        });
      },
      //更新nacos路由配置
      updateRoutes(routesData) {
        var data = this.convertData(routesData);
        if(data){
          SysRoutingApi.publish(data);
        }
      },
      //截取字符串
      substr(ary,str,count){
        var index=str.indexOf("}");
        var subStr=str.substring(0,index+1);
        ary.push(subStr);
        var remain=str.substring(index+2,str.length);
        if (count-1>1){
          ary=this.substr(ary,remain,count-1);
        }else {
          ary.push(remain);
        }
        return ary;
      },
      //转换数据
      convertData(routesData) {
        var predicates = [];
        var filters = [];
        var predicateList = this.$refs.predicates.predicateList;
        var filterList = this.$refs.filters.filterList;
        for (var i = 0; i < predicateList.length; i++) {
          var predicateObj = {
            name: predicateList[i].predicateName,
            args: JSON.parse(predicateList[i].predicateArgs)
          };
          predicates.push(predicateObj);
        }
        for (var i = 0; i < filterList.length; i++) {
          var filterObj = {
            name: filterList[i].filterName,
            args: JSON.parse(filterList[i].filterArgs)
          };
          filters.push(filterObj);
        }
        const {requestData} = this;
        var data = [];
        for (var i = 0; i < requestData.length; i++) {
          data.push(requestData[i]);
        }
        var flag=true;
        //新增
        if (this.type == "add") {
          if(routesData.status=="0"){
            flag=false;
            return ;
          }
        } else {
          //禁用
          if(routesData.status=="0"){
            for (var i = 0; i < data.length; i++) {
              if (data[i].id == routesData.id) {
                data.splice(i, 1);
              }
            }
            flag=false;
          }else {
            for (var i = 0; i < data.length; i++) {
              if (data[i].id == routesData.id) {
                data[i].uri = routesData.uri;
                data[i].predicates = predicates;
                data[i].filters = filters;
                flag=false;
              }
            }
          }
        }
        if(flag){
          data.push({
            id: routesData.id,
            predicates: predicates,
            filters: filters,
            uri: routesData.uri
          });
        }
        return data;
      },
    }
  }
</script>
